<template>
    <div id="create-edit-container">
        <!-- use the modal component, pass in the prop -->
        <Modal v-model="stateManager.editDialogVisible"
               :title="modalTitle"
               width="60%"
               @on-cancel="closeDialog"
               :styles="{top: '20px'}"
               :mask-closable="false">

            <i-form ref="model" :model="model" :rules="ruleValidate">
                <Row type="flex">
                    <i-col span="24">
                        <Form-item label="排序" prop="sort">
                            <Input-number :min="1" :max="50" v-model="model.sort" style="width: 100%"></Input-number>
                        </Form-item>
                    </i-col>
                    <i-col span="24">
                        <Form-item label="上传图片" prop="file_id">
                            <Upload type="drag" action="api/famous-school/file-upload"
                                    ref="upload"
                                    :headers="uploadHeaders"
                                    :on-success="uploadSuccessCallback"
                                    :on-error="uploadFailedCallback"
                                    :max-size="10240"
                                    :format="['jpg', 'jpeg', 'png']"
                                    style="margin-top: 40px">
                                <div style="padding: 20px 0" v-if="model.path == ''">
                                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                    <p>点击或将文件拖拽到这里上传</p>
                                </div>
                                <div v-else>
                                    <img :src="imgBaseUrl + '/' + model.path" style="max-width: 100%">
                                </div>
                                <template slot="tip">
                                    <h5 v-if="model.sort == 1">请上传尺寸为1158*317格式为jpg，jpeg，png的图片！（大小不超过10M）</h5>
                                    <h5 v-if="model.sort > 1">请上传尺寸为283*285格式为jpg，jpeg，png的图片！（大小不超过10M）</h5>
                                </template>
                            </Upload>
                            <i-input type="text" v-model="model.file_id" hidden></i-input>
                        </Form-item>
                    </i-col>
                </Row>

            </i-form>

            <template slot="footer">
                <Row type="flex">
                    <i-col span="24">
                        <div class="pull-right">
                            <i-button type="ghost" @click="closeDialog">取消</i-button>
                            <i-button type="primary" @click="saveModel" :loading="isLoading">确定</i-button>
                        </div>
                    </i-col>
                </Row>
            </template>

        </Modal>

    </div>


</template>

<script>
    export default {
        props: {
            stateManager: {
                type: Object
            }
        },
        data: function () {
            return {
                model: this.$modelDataSource({
                    url: 'api/famous-school',
                    dataKey: 'model',
                    attributes: {
                        id: 0,
                        sort: 1,
                        file_id: '',
                        path: ''
                    }
                }),
                uploadHeaders: window.uploadHeaders,
                isLoading: false,
                ruleValidate: {
                    sort: [
                        { required: true, type: 'number', message: '排序为正整数，请输入有效的数字', trigger: 'blur' }
                    ],
                    file_id: [
                        { required: true, type: 'number', message: '请上传有效格式的图片', trigger: 'blur' }
                    ]
                }
            };
        },
        created: function () {
        },
        methods: {
            closeDialog: function () {
                this.stateManager.editDialogVisible = false;
                this.model.reset();
                this.$refs['model'].resetFields();
                this.$refs['upload'].clearFiles();
                this.stateManager.editModelId = 0;
            },
            uploadSuccessCallback: function (response, file) {
                //上传成功回调
                console.log(file);
                console.log(response);
                if (response.status == 'success'){
                    this.model.file_id = response.file_id;
                    this.model.path = response.path;
                }
            },
            uploadFailedCallback: function (error, file) {
                //上传失败回调
                console.log(error);
                console.log(file);
            },
            saveModel: function () {
                let self = this;
                self.$refs['model'].validate((valid) => {
                    if (valid){
                        console.log('表单验证通过');
                        self.isLoading = true;
                        self.model.save(function () {
                            self.isLoading = false;
                            self.$Notice.success({
                                title: '保存成功',
                                desc: ''
                            });
                            self.closeDialog();
                            self.stateManager.refreshList = true;
                        }, function () {
                            console.log(self.model.errors);
                            self.isLoading = false;
                            _.forOwn(self.model.errors, function (value, key) {
                                if (value){
                                    self.$Notice.error({
                                        title: '保存失败',
                                        desc: value
                                    });
                                }
                            });
                        });
                    }else{
                        console.log('表单验证失败');
                    }
                })
            }
        },
        computed: {
            modalTitle: function () {
                if (this.model.id === 0){
                    return '添加名校';
                }else{
                    return '修改名校';
                }
            },
            imgBaseUrl(){
                return window.Laravel.imgBaseUrl;
            }
        },
        watch: {
            'stateManager.editModelId': function (newValue) {
                let self = this;
                this.model.fetch(newValue, function () {
                    self.stateManager.buttonLoading = false;
                    self.stateManager.editDialogVisible = true;
                }, function () {
                    self.stateManager.buttonLoading = false;
                    self.$Notice.error({
                        title: '数据加载超时',
                        desc: '请尝试刷新页面，并仔细检查网络链接状况或联系技术人员！'
                    });
                });
            }
        }
    }
</script>